<?php

namespace app\api\controller;
use think\facade\Db;
use think\facade\Request;
use app\admin\controller\Admin;
class Permission
{
    //获取当前登录用户的权限
    public function adminPermission()
    {
        $admin = new Admin();
        $decodeToken = $admin->decodeToken();
        $obj = (string)$decodeToken;
        $da = json_decode($obj, true);
        $das = $da['data'];
        $admin_id=$das['adminId'];
        $permissionData=Db::table('admin')->alias('a')->where('a.id',$admin_id)
                                ->join(['admin_roles' => 'r'], 'a.role_id = r.id')
                                ->field('r.permissions')->select()->toArray();
        $permissionData=$permissionData[0]['permissions'];
        $permissionData=json_decode($permissionData,true);
        $result = Db::name('menus')
                        ->whereIn('id', $permissionData)
                        ->field('id,name,url,parentId,listorder')
                        ->select()
                        ->toArray();
        return json([
            'code' =>200,
            'data' =>$result,
        ]);
    }

    public function adminList()
    {
        $pageData=Request::param();
        $page = $pageData['page'];
        $perPage=$pageData['pageSize'];
        
        if(isset($pageData['time'][0])){
            $start_time=$pageData['time'][0];
        }else{
            $start_time='';
        }
        if(isset($pageData['time'][1])){
            $end_time=$pageData['time'][1];
        } else{
            $end_time='';
        }
        
        if(isset($pageData['keyword'])){
            $phone=$pageData['keyword'];
        } else{
            $phone='';
        }

        $query=Db::table('admin')->alias('a')
                                ->join(['admin_roles' => 'r'], 'a.role_id = r.id')
                                ->field('a.*, r.role_name');
        if ($start_time) {
            $query=$query->where('a.create_time', '>=', $start_time);
        }
        // 如果 end_time 存在，则添加条件
        if ($end_time) {
            $query=$query->where('a.create_time', '<=', $end_time);
        }
        // 如果 xiangmuming 存在，则进行模糊查询
        if ($phone) {
              $query = $query->where(function ($q) use ($phone) {
                // 同时匹配手机号（phone）和姓名（name），满足任一即可
                $q->where('phone', 'like', "%{$phone}%")
                ->whereOr('adminName', 'like', "%{$phone}%");
            });
        }
        $userData=$query
                ->order('a.create_time','desc')
                ->paginate([
                        'list_rows' => $perPage,
                        'page'      => $page,
                    ]);
        $data=$userData;
        if (!$data) {
                return json(['
                message' => '没有数据', 
                'data' => '', 
                'code' => 200
            ]);
        } else {
            return json([
                'message' => '数据查询成功',
                'code'    => 200,
                'data'    => $data,
            ]);
        }
    }

    //状态修改
    public function changeStatus()
    {

        $id=Request::param('id');
        $adminData=Db::table('admin')->where('id',$id)->find();
        if($adminData['status']==1){
            Db::table('admin')->where('id',$id)->update(['status'=>0,'update_time'=>date('Y-m-d H:i:s')]);
        }else{
            Db::table('admin')->where('id',$id)->update(['status'=>1,'update_time'=>date('Y-m-d H:i:s')]);
        }

        return json([
            'code' =>200,
            'message' =>'操作成功',
        ]);
    }

    public function adminAdd()
    {
        $adminData = Request::param();
        
        // 检查手机号是否已存在
        $data = Db::table('admin')->where('phone', $adminData['phone'])->find();
        if ($data) {
            return json([
                'code' => 400,
                'message' => '添加失败，用户已经存在',
            ]);
        }
        
        $insertData['phone'] = $adminData['phone'];
        $insertData['password'] = md5($adminData['password']);
        $insertData['outpassword'] = $adminData['outpassword'];
        $insertData['create_time'] = date('Y-m-d H:i:s');
        $insertData['update_time'] = date('Y-m-d H:i:s');
        $insertData['role_id'] = $adminData['role_id'];
        $insertData['adminName']  =$adminData['adminName'];
        $res = Db::table('admin')->insert($insertData);
        if ($res) {
            return json([
                'code' => 200,
                'message' => '添加成功',
            ]);
        } else {
            return json([
                'code' => 403,
                'message' => '添加失败',
            ]);
        }
    }

    // 商户号生成方法
    private function generateMerchantNumber()
    {
        // 生成前两位字母（大小写混合，若需要纯大写可去掉小写字母）
        $letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        $prefix = '';
        for ($i = 0; $i < 2; $i++) {
            $prefix .= $letters[rand(0, strlen($letters) - 1)];
        }
        
        // 生成后八位数字
        $suffix = '';
        for ($i = 0; $i < 8; $i++) {
            $suffix .= rand(0, 9);
        }
        
        return $prefix . $suffix;
    }

    

    //分组列表
    public function groupList()
    {
        $groupData=Db::table('admin_roles')->field('id,role_name')->where('status',1)->select()->toArray();
        return json([
            'code'    => 200,
            'data'    => $groupData,
            'message' => '查询成功',
        ]);
     }
    public function adminEdit()
    {
        $adminData=Request::param();
        $id=$adminData['id'];
        $newData['role_id']=$adminData['role_id'];
        if(isset($adminData['password'])){
            $newData['password']=md5($adminData['password']);
            $newData['outpassword']=$adminData['password'];
        }
        $newData['update_time']=date('Y-m-d H:i:s');
        $newData['adminName'] = $adminData['adminName'];
        $res=Db::table('admin')->where('id',$id)->update($newData);
        if($res){
            return json([
                'code' =>200,
                'message'=>'更新成功',
            ]);
        }else{
            return json([
                'code' =>403,
                'message'=>'更新失败',
            ]);
        }

    }
    public function adminDel()
    {
        $id=Request::param('id');
        $res=Db::table('admin')->where('id',$id)->delete();
        if($res){
                return json([
                'code'   =>200,
                'message'=>'删除成功',
            ]);
        }else{
            return json([
                'code'   =>400,
                'message'=>'删除失败',
            ]);
        }
    }

    public function adminGroupList()
    {
        $pageData=Request::param();
        $page = $pageData['page'];
        $perPage=$pageData['pageSize'];
        
        if(isset($pageData['time'][0])){
            $start_time=$pageData['time'][0];
        }else{
            $start_time='';
        }
        if(isset($pageData['time'][1])){
            $end_time=$pageData['time'][1];
        } else{
            $end_time='';
        }
        
        if(isset($pageData['keyword'])){
            $role_name=$pageData['keyword'];
        } else{
            $role_name='';
        }

        $query=Db::table('admin_roles');
        if ($start_time) {
            $query=$query->where('create_time', '>=', $start_time);
        }
        // 如果 end_time 存在，则添加条件
        if ($end_time) {
            $query=$query->where('create_time', '<=', $end_time);
        }
        // 如果 xiangmuming 存在，则进行模糊查询
        if ($role_name) {
            $query=$query->where('role_name', 'like', '%'.$role_name. '%');
        }
        $userData=$query
                ->order('create_time','desc')
                ->paginate([
                        'list_rows' => $perPage,
                        'page'      => $page,
                    ]);
        $data=$userData;
        if (!$data) {
                return json(['
                message' => '没有数据', 
                'data' => '', 
                'code' => 200
            ]);
        } else {
            return json([
                'message' => '数据查询成功',
                'code'    => 200,
                'data'    => $data,
            ]);
        }

    }
    public function groupChangeStatus()
    {
        $id=Request::param('id');
        $adminData=Db::table('admin_roles')->where('id',$id)->find();
        if($adminData['status']==1){
            Db::table('admin_roles')->where('id',$id)->update(['status'=>0,'update_time'=>date('Y-m-d H:i:s')]);
            //禁用所有的对应组的管理员状态
            Db::table('admin')->where('role_id',$id)->update(['status'=>0,'update_time'=>date('Y-m-d H:i:s')]);
        }else{
            Db::table('admin_roles')->where('id',$id)->update(['status'=>1,'update_time'=>date('Y-m-d H:i:s')]);
            Db::table('admin')->where('role_id',$id)->update(['status'=>1,'update_time'=>date('Y-m-d H:i:s')]);
        }

        return json([
            'code' =>200,
            'message' =>'操作成功',
        ]);

    }
    public function adminGroupDel()
    {
        $id=Request::param('id');
        $res=Db::table('admin_roles')->where('id',$id)->delete();
        if($res){
                return json([
                'code'   =>200,
                'message'=>'删除成功',
            ]);
        }else{
            return json([
                'code'   =>400,
                'message'=>'删除失败',
            ]);
        }

    }
    //权限即菜单获取
    public function permissionList()
    {
        $permissionData=Db::name('menus')->field('id,name,parentId,listorder')->select()->toArray();
        return json([
                'code'   =>200,
                'data'=>$permissionData,
        ]);
    }
    public function adminGroupAdd()
    {
        $adminGroupData=Request::param();
        $insertData['role_name']=$adminGroupData['role_name'];
        $insertData['create_time']=date('Y-m-d H:i:s');
        $insertData['update_time']=date('Y-m-d H:i:s');
        $insertData['status']=$adminGroupData['status'];
        $permissions=json_encode($adminGroupData['permissions']);
        $insertData['permissions']=$permissions;
        $res=Db::table('admin_roles')->insert($insertData);
        if($res){
            return json([
                'code' =>200,
                'message'=>'添加成功',
            ]);
        }else{
            return json([
                'code' =>403,
                'message'=>'添加失败',
            ]);
        }
        

    }
    public function adminGroupEdit()
    {
        $adminGroupData=Request::param();
        $id=$adminGroupData['id'];
        $newData['role_name']=$adminGroupData['role_name'];
        $newData['permissions']=json_encode($adminGroupData['permissions']);
        $newData['update_time']=date('Y-m-d H:i:s');
        $newData['status']=$adminGroupData['status'];
        $res=Db::table('admin_roles')->where('id',$id)->update($newData);
        if($res){
            return json([
                'code' =>200,
                'message'=>'更新成功',
            ]);
        }else{
            return json([
                'code' =>403,
                'message'=>'更新失败',
            ]);
        }
    }
}